package com.zwz.crawler.productdata;

import com.zwz.constant.Constant;
import com.zwz.entity.SoftwareRegistry;
import com.zwz.parse.JsonParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.zwz.constant.Constant.ENTERPRISE_ID;

@Slf4j
public class TungeeSoftwareQuery {
    // 固定参数配置
//    private static final String ENTERPRISE_ID = "577de19eadf21dc4";
    private static final int START = 0;
    private static final int END = 5;

    public static List<SoftwareRegistry> startTungeeSoftwareQuery( String ENTERPRISE_ID) {
        // 参数有效性校验
        if (START < 0 || END <= START || (END - START) > 100) {
            throw new IllegalArgumentException("分页参数不合法，要求：start >=0 且 end > start 且差值 ≤100");
        }

        try {
            // 构建URL（强制URL编码）
            String encodedId = URLEncoder.encode(ENTERPRISE_ID, String.valueOf(StandardCharsets.UTF_8));
            String url = String.format(
                    "https://sales.tungee.com/api/enterprise/%s/intellectual-property/software?start=%d&end=%d",
                    encodedId, START, END
            );

            // 发送请求
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 请求头精确配置（顺序与浏览器一致）
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
                    .header("cookie", Constant.cookies)
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/intellectual-property")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    // 连接配置
                    .ignoreContentType(true)  // 允许接收JSON等非HTML内容
                    .ignoreHttpErrors(true)  // 不抛出HTTP错误异常
                    .maxBodySize(0)         // 禁用响应体大小限制
                    .timeout(30_000)        // 30秒超时
                    .execute();

            // 处理响应
            processResponse(response);

            //解析
            List<SoftwareRegistry> ret = JsonParserUtil.ParseSoft(response.body());

            return ret;


        } catch (IOException e) {
            handleNetworkException(e);
        }
        return null;
    }

    private static void processResponse(Connection.Response response) {
       log.info("=== 响应状态 ===");
       log.info("HTTP状态码: " + response.statusCode());
       log.info("URL: " + response.url());

        // 根据状态码处理
        switch (response.statusCode()) {
            case 200:
//               log.info("\n=== 软件著作权数据 ===");
               log.info(response.body());
                break;
            case 401:
                System.err.println("[认证过期] 解决方案：");
                System.err.println("1. 检查Cookie中的accountCenterSessionId和doncusSessionId");
                System.err.println("2. 通过浏览器登录后更新Cookie值");
                break;
            case 403:
                System.err.println("[权限不足] 可能原因：");
                System.err.println("1. 当前账户无知识产权数据访问权限");
                System.err.println("2. 企业ID " + ENTERPRISE_ID + " 不属于当前账户");
                break;
            case 429:
                System.err.println("[请求频繁] 建议：");
                System.err.println("1. 添加5-8秒随机延时");
                System.err.println("2. 使用代理IP轮换策略");
                break;
            default:
                System.err.println("未知错误状态码: " + response.statusCode());
                System.err.println("响应内容: " + response.body());
        }
    }

    private static void handleNetworkException(IOException e) {
        System.err.println("\n=== 网络异常 ===");
        if (e.getMessage().contains("timed out")) {
            System.err.println("连接超时，建议：");
            System.err.println("1. 检查网络连接");
            System.err.println("2. 增加超时时间（如60秒）");
        } else if (e.getMessage().contains("Connection refused")) {
            System.err.println("连接被拒绝，可能原因：");
            System.err.println("1. 本地防火墙限制");
            System.err.println("2. 代理服务器配置错误");
        } else {
            System.err.println("未知网络错误：");
            e.printStackTrace();
        }
    }

    // 增强功能：动态Cookie刷新（需登录接口）
//    private static Map<String, String> refreshCookies() throws IOException {
//        return Jsoup.connect("https://user.tungee.com/login")
//                .data("phone", "您的账号")
//                .data("password", "加密后的密码")
//                .method(Connection.Method.POST)
//                .execute()
//                .cookies();
//    }
}